<script lang="ts" setup>
import { getCurrentInstance, reactive, ref } from 'vue'
import { onLoad, onPageScroll, onReady } from '@dcloudio/uni-app'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import PageContainer from '@/components/page-container/index.vue'
import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js'
import { useScrollTransparentNavbar } from '@/hooks'
import user from '@/api/user.js'
import { FILE_URL, USER_INFO, USER_TOKEN, MP_API_URL } from '@/api/config.js'

const paging = ref(null)
useZPaging(paging)
// 导航栏的高度
const navbarHeight = ref(0)
const instance = getCurrentInstance()
const state = reactive({
  userInfo: '',
  userToken: '',
  chatsId: 0,
  sendUserId: 0,
  receiveUserId: 0,
  receiveUserNickname: '',
  content: '',
  msgType: 'text',
  messageLists: [],
  top: 0,
  isKeyboardVisible: false,
})
const { init: initTransparentScroll, opacityScrollHandle } =
  useScrollTransparentNavbar(instance)
// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}

const focusEvent = () => {
  state.isKeyboardVisible = true
  state.msgType = 'text'
}

const blurEvent = () => {
  if (state.conotent == '') {
    state.isKeyboardVisible = false
  }
}
const previewImage = (image) => {
  uni.previewImage({
    current: 0,
    urls: [FILE_URL + image]
  })
}
const queryList = (pageNo: any, pageSize: any) => {
  user
    .chatDetail({
      chats_id: state.chatsId,
      page: pageNo,
      page_size: pageSize,
    })
    .then((res) => {
      console.log(res.data, 'userFansList')
      paging.value.complete(res.data)
    })
    .catch((err: any) => {
      console.log(err, 'userFansList')
      paging.value.complete(false)
    })
}
const send = () => {
  _sendChatMessages(state.content)
  scrollToBottom()
}

const chooseImage = () => {
  state.msgType = 'image'
  uni.chooseImage({
    count: 1,
    success(res) {
      if (res.errMsg == 'chooseImage:ok') {
        const tempFilePaths = res.tempFilePaths
        uni.uploadFile({
          url: `${MP_API_URL}/system.System/upload`,
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            Authorization: uni.getStorageSync(USER_TOKEN),
          },
          formData: {
            typeEnum: 'IMAGE',
          },
          success(uploadFileRes) {
            const result = JSON.parse(uploadFileRes.data)
            if (result.code == 1) {
              _sendChatMessages(result.data.file.url)
              scrollToBottom()
            }
          },
          fail(uploadFileErr) {
            console.log(uploadFileErr)
            uni.showToast({
              title: uploadFileErr,
              icon: 'none',
            })
          },
        })
      }
    },
  })
}

const _sendChatMessages = (sendContent: string) => {
  user
    .sendChatMessages({
      receive_user_id: state.receiveUserId,
      content: sendContent,
      msg_type: state.msgType,
    })
    .then((res) => {
      if (res.code == 1) {
        state.messageLists.push({
          content: state.content,
          msg_type: state.msgType,
          user_type: 'self',
          avatar: state.userInfo.avatar,
        })
        state.content = ''
      }
    })
    .catch((err: any) => {
      console.log(err, 'sendChatMessages')
    })
}

const scrollToBottom = () => {
  state.top = state.messageLists.length * 1000
}
onLoad((options) => {
  if (!options?.receiveUserId) {
    uni.showModal({
      title: '提示',
      content: '参数错误',
      showCancel: false,
      success: () => {
        uni.navigateBack()
      },
    })
    return
  }
  state.chatsId = options.chatsId
  state.receiveUserId = options.receiveUserId
  state.receiveUserNickname = options.receiveUserNickname
  const userInfo = uni.getStorageSync(USER_INFO)
  if (userInfo) {
    state.userInfo = userInfo
    state.sendUserId = userInfo.id
  }
  state.userToken = uni.getStorageSync(USER_TOKEN)
})
onReady(() => {
  initTransparentScroll()
})
onPageScroll((e) => {
  opacityScrollHandle(e.scrollTop)
})
</script>

<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      :bottom-shadow="false"
      :placeholder="false"
      @init-finish="navbarInitFinishHandle"
    >
      <text class="tn-text-bold">{{ state.receiveUserNickname }}</text>
    </TnNavbar>
    <view class="container tn-mt-sm">
      <z-paging
        ref="paging"
        v-model="state.messageLists"
        :paging-style="{ paddingTop: `${navbarHeight + 10}px` }"
        :safe-area-inset-bottom="true"
        :use-safe-area-placeholder="true"
        @query="queryList"
      >
        <view class="page">
          <scroll-view
            class="scroll-view"
            scroll-y
            scroll-with-animation
            :scroll-top="state.top"
          >
            <view style="padding: 30rpx 30rpx 240rpx">
              <view
                v-for="(item, index) in state.messageLists"
                :key="index"
                class="message"
                :class="[item.user_type]"
              >
                <image
                  v-if="item.user_type == 'friend'"
                  :src="FILE_URL + item.avatar"
                  class="avatar"
                  mode="widthFix"
                />
                <view v-if="item.msg_type == 'image'" class="content">
                  <image
                    :src="FILE_URL + item.content"
                    mode="widthFix"
                    @click="previewImage(item.content)"
                  />
                </view>
                <view v-else class="content">
                  {{ item.content }}
                </view>
                <image
                  v-if="item.user_type == 'self'"
                  :src="FILE_URL + item.avatar"
                  class="avatar"
                  mode="widthFix"
                />
              </view>
            </view>
          </scroll-view>
          <view class="tool">
            <input
              v-model="state.content"
              type="text"
              class="input"
              @confirm="send"
              @focus="focusEvent"
              @blur="blurEvent"
            />
            <TnButton
              v-if="state.isKeyboardVisible"
              text-color="#FFFFFF"
              font-size="26"
              :custom-style="{ padding: '20rpx 18rpx' }"
              @tap.stop="send"
            >
              发送
            </TnButton>
            <image
              v-else
              src="@/static/images/photo.png"
              mode="widthFix"
              class="thumb"
              @tap.stop="chooseImage"
            />
          </view>
        </view>
      </z-paging>
    </view>
  </PageContainer>
</template>

<style lang="scss" scoped>
@use './styles/chats.scss';
</style>
